package com.chengwei.ch.busdemo;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import com.chengwei.ch.busdemo.activity.VideoActivity;
import com.chengwei.ch.busdemo.base.BaseActivity;
import com.chengwei.ch.busdemo.hermes.contract.Hermes;
import com.chengwei.ch.busdemo.hermes.contract.OnConnectListener;
import com.chengwei.ch.busdemo.hermes.modules.HermesAgent;
import com.chengwei.ch.busdemo.network.NetworkLiveData;
import com.chengwei.ch.busdemo.stomp.Header;
import com.chengwei.ch.busdemo.stomp.Stomp;
import com.chengwei.ch.busdemo.view.Screensaver;
import com.ejlchina.okhttps.OkHttps;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.unit.Subunits;

public class APP extends Application implements Screensaver.OnTimeOutListener {

    public static APP app;
    public static Screensaver mScreensaver;
    public static Stomp stomp = null;
    public static Hermes mHermes = null;
    private List<BaseActivity> activityList = new ArrayList<BaseActivity>();

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        mScreensaver = new Screensaver(5 * 1000); //定时5秒
        mScreensaver.setOnTimeOutListener(this); //监听
        //mScreensaver.start(); //开始时间
        //startService();
        initAutoSize();
        getHermes();
        NetworkLiveData.get(this).onActive();
    }

    /**
     * 今日头条适配
     */
    private void initAutoSize() {
        AutoSizeConfig.getInstance()
                .setBaseOnWidth(false)
                .getUnitsManager()
                .setSupportDP(true)
                .setSupportSP(false)
                .setSupportSubunits(Subunits.NONE);
    }

    /**
     * activity入栈
     *
     * @param activity 入栈的activity
     */
    public void pushActivity(BaseActivity activity) {
        if (!activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    /**
     * activity弹栈
     *
     * @param activity 弹栈的activity
     */
    public void popActivity(BaseActivity activity) {
        activityList.remove(activity);
    }

    /**
     * 关闭所有activity
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void closeAllActivity() {
        if (activityList.size() > 0) {
            for (BaseActivity it : activityList) {
                if (it.isDestroyed()) {
                    it.finish();
                }
            }
            activityList.clear();
        }
    }


    /**
     * 退成app进程时，执行该方法
     * 结束倒计时
     */

    public void exitApp() {
        mScreensaver.stop();
        mScreensaver = null;
        closeAllActivity();
        if (stomp != null) {
            stomp.disconnect(true);
            stomp = null;
        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 时间到就会执行此方法
     */
    @Override
    public void onTimeOut(Screensaver screensaver) {
        Log.d("MainActivity", "时间到了");
        try {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), VideoActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        } catch (Throwable e) {
            Log.d("MainActivity", e.toString());
        }
    }

    private Boolean isReconnection = false;
    private Boolean isStartService = false;

    /**
     * 初始化stomp协议
     *
     * @isReconnection true断网重连, false表示没有断网
     * @isStartService true开启服务, false暂停服务
     */
    private void initStomp() {
        // 使用一个 Websocket 连接构建一个 Stomp 实例，同时设置心跳间隔为 20 秒
        List<Header> headers = new ArrayList<>();
        headers.add(new Header("login", "han"));
        headers.add(new Header("passcode", "han"));
        headers.add(new Header("accept-version", "1.1,1.0"));
        headers.add(new Header("heart-beat", "5000,10000"));
        headers.add(new Header("host", "/"));
        //        这里必须添加headers 否则会报错 headers可以添加用户的认证相关信息
        //连接监听
        stomp = Stomp.over(
                OkHttps
                        .webSocket("ws://qy.cvimp.cn:25674/ws")
                        .heatbeat(20, 20)
                        .nothrow())
                .setOnConnected(stomp -> {
                    // 服务器连接成功回调
                    Log.d("BaseActivity", "-->连接成功:");
                    if (isReconnection && isStartService) {
                        stopService();
                        try {
                            Thread.sleep(500);
                            startService();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setOnDisconnected(close -> {
                    stomp = null;
                    // 连接已断开回调
                    Log.d("BaseActivity", "-->连接断开:" + close);
                    //重连机制
                    if (close.getCode() == 0 || close.getCode() == -2 || close.getCode() == -3) {
                        isReconnection = true;
                        if (isStartService) {
                            try {
                                Thread.sleep(5000);
                                initStomp();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } else isReconnection = false;
                })
                .setOnError(msg -> {
                    stomp = null;
                    // 错误监听（v2.4.1 新增）
                    // 处理服务器发出的 ERROR 帧
                    Log.d("BaseActivity", "-->连接异常$" + msg);
                })
                .connect(headers);
    }

    /**
     * 开启服务
     */
    public void startService() {
        isStartService = true;
        if (stomp == null) {
            initStomp();
        }
    }

    /**
     * 停止服务
     */
    private void stopService() {
        isStartService = false;
    }


    /**
     * 连接MQTT
     */
    public void getHermes() {
        //TODO->获取手机设备唯一id
        String appDeviceId = "zdk-12232323232324";
        //TODO->连接MQTT服务器
        mHermes = HermesAgent.create()
                .setConnectType(HermesAgent.MQTT)
                .setUrl("tcp://192.168.88.191:39844")
                .setClientId(appDeviceId)
                .setPrintLog(true)
                .setLogTag("HermesLog")
                .setOnConnectListener(new OnConnectListener() {
                    @Override
                    public void onConnectComplete(boolean isReconnected) {
                        Log.d("Tag", "连接完成 ： isReconnected ---> " + isReconnected);
                    }

                    @Override
                    public void onConnectFailure(Throwable cause) {
                        Log.d("Tag", "连接失败 : " + cause.getMessage());
                    }

                    @Override
                    public void onConnectionLost(Throwable cause) {
                        Log.d("Tag", "连接断开（丢失） : " + cause.getMessage());
                    }
                })
                .buildConnect(this);
    }

    /**
     * 退出MQTT连接
     */
    public void exitHermes() {
        if (mHermes != null && mHermes.isConnected()) {
            mHermes.disconnect();
            mHermes = null;
        }
    }
}
